<?php

namespace plugin\admin\app\controller;

use app\services\CustomerService;
use support\Request;
use support\Response;
use plugin\admin\app\model\Message;
use plugin\admin\app\controller\Crud;
use support\exception\BusinessException;

/**
 * 客服消息 
 */
class MessageController extends Crud
{
    
    /**
     * @var Message
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new Message;
    }
    
    /**
     * 浏览
     * @return Response
     */
    public function index(Request $request): Response
    {
        return view('message/index', [
            'userId' => $request->get('user_id'),
        ]);
    }

    public function addMessage(Request $request)
    {
        CustomerService::add($request->post('user_id'), $request->post('type'), $request->post('content'));

        return $this->json(0, 'ok');
    }

    public function getList(Request $request)
    {
        $messages = CustomerService::list($request->get('user_id'), 1, 0, false);

        $html = '<div class="message-wrapper">';

        foreach ($messages as $message) {
            if ($message['role'] == 1) {
                $roleClass = 'self';
            } else {
                $roleClass = 'target';
            }

            if ($message['message_type'] == 1) {
                $typeClass = 'text';
                $content = $message['content'];
            } else {
                $typeClass = 'image';
                $content = '<img src="' . $message['content'] . '" width="100" />';
            }

            $html .= <<< EOF
<div class="message-item-wrapper {$roleClass}">
    <div class="message $typeClass">{$content}</div>
</div>
EOF;

        }

        $html .= '</div>';

        return $this->json(0, 'ok', ['data' => $html]);
    }

    /**
     * 插入
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::insert($request);
        }
        return view('message/insert');
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
    */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::update($request);
        }
        return view('message/update');
    }

    protected function formatNormal($items, $total): Response
    {


        return json(['code' => 0, 'msg' => 'ok', 'count' => $total, 'data' => $items]);
    }
}
